package com.training.controller;

import com.training.entity.*; // 导入所有 entity
import com.training.dto.CommentDisplayDto;
import com.training.service.*; // 导入所有 service
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Controller
@RequestMapping("/course")
public class CourseController {

    private static final Logger logger = LoggerFactory.getLogger(CourseController.class);

    private final CourseService courseService;
    private final ChapterService chapterService;
    private final CommentService commentService;
    private final StudentService studentService;
    private final TeacherService teacherService;
    private final OfflinePracticeService practiceService; // 1. 新增注入 OfflinePracticeService

    @Autowired
    public CourseController(CourseService courseService, ChapterService chapterService,
                            CommentService commentService, StudentService studentService,
                            TeacherService teacherService, OfflinePracticeService practiceService) { // 2. 在构造函数中接收
        this.courseService = courseService;
        this.chapterService = chapterService;
        this.commentService = commentService;
        this.studentService = studentService;
        this.teacherService = teacherService;
        this.practiceService = practiceService; // 3. 完成注入
    }

    /**
     * Display the course management page for the logged-in teacher.
     * Original function: retrieve all courses for the teacher.
     *
     * @param model Model to pass data to the view
     * @param session HttpSession to get logged-in user info
     * @return The course management page view
     */
    @GetMapping("/manage")
    public String manageCourses(Model model, HttpSession session) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null) {
            return "redirect:/login";
        }

        // 获取教师ID
        Long teacherId = teacherService.getTeacherIdByUserId(loggedInUser.getId());
        if (teacherId == null) {
            logger.warn("User ID {} is not a recognized teacher. Access denied to course management.", loggedInUser.getId());
            model.addAttribute("errorMessage", "您不是教师，无法管理课程。");
            return "error"; // 或者跳转到其他合适的错误页面
        }

        List<Course> courses = courseService.getCoursesByTeacherId(teacherId);
        model.addAttribute("courses", courses);
        model.addAttribute("loggedInUser", loggedInUser);
        logger.info("Teacher ID {} accessed course management page. Found {} courses.", teacherId, courses.size());
        return "course-manage";
    }

    /**
     * API endpoint to search courses by keyword for the logged-in teacher.
     * Returns a JSON list of courses. This is for AJAX calls from the frontend.
     *
     * @param keyword The search keyword for course name (optional).
     * @param session HttpSession to get logged-in user info.
     * @return A list of Course objects in JSON format.
     */
    @GetMapping("/api/search")
    @ResponseBody // This annotation makes Spring return the object as JSON directly.
    public List<Course> searchCoursesApi(@RequestParam(value = "keyword", required = false) String keyword,
                                         HttpSession session) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null) {
            // 如果用户未登录，返回空列表或一个错误状态码 (前端会处理)
            logger.warn("Unauthenticated access to course search API.");
            return Collections.emptyList(); // 使用 Collections.emptyList() 避免返回 null
        }

        Long teacherId = teacherService.getTeacherIdByUserId(loggedInUser.getId());
        if (teacherId == null) {
            logger.warn("User ID {} is not a recognized teacher. Access denied to course search API.", loggedInUser.getId());
            return Collections.emptyList();
        }

        List<Course> courses;
        if (keyword != null && !keyword.trim().isEmpty()) {
            courses = courseService.searchCoursesByTeacherIdAndName(teacherId, keyword.trim());
            logger.info("Teacher ID {} searched courses with keyword '{}'. Found {} courses.", teacherId, keyword, courses.size());
        } else {
            // 如果关键词为空，则返回所有课程（保持原有功能）
            courses = courseService.getCoursesByTeacherId(teacherId);
            logger.info("Teacher ID {} retrieved all courses without keyword. Found {} courses.", teacherId, courses.size());
        }
        return courses;
    }


    /**
     * Display the course creation form.
     * @param model Model to pass data to the view
     * @param session HttpSession to get logged-in user info
     * @return The course add page view
     */
    @GetMapping("/add")
    public String addCourseForm(Model model, HttpSession session) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null) {
            return "redirect:/login";
        }
        Long teacherId = teacherService.getTeacherIdByUserId(loggedInUser.getId());
        if (teacherId == null) {
            logger.warn("User ID {} is not a recognized teacher. Access denied to add course form.", loggedInUser.getId());
            return "redirect:/error-page";
        }

        model.addAttribute("course", new Course());
        model.addAttribute("loggedInUser", loggedInUser); // 添加用户信息
        logger.info("Teacher ID {} is accessing add course form.", teacherId);
        return "course-add";
    }

    /**
     * Handle course creation form submission.
     * @param course Course object from the form
     * @param couPicFile MultipartFile for course cover image
     * @param session HttpSession to get logged-in user info
     * @param redirectAttributes RedirectAttributes for flash messages
     * @return Redirect to course management page or back to form
     */
    @PostMapping("/add")
    public String addCourse(@ModelAttribute("course") Course course,
                            @RequestParam(value = "couPicFile", required = false) MultipartFile couPicFile,
                            HttpSession session,
                            RedirectAttributes redirectAttributes) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null) {
            return "redirect:/login";
        }

        Long teacherId = teacherService.getTeacherIdByUserId(loggedInUser.getId());
        if (teacherId == null) {
            redirectAttributes.addFlashAttribute("errorMessage", "您无权添加课程，因为您不是注册教师。");
            logger.warn("User ID {} is not a recognized teacher. Failed to add course.", loggedInUser.getId());
            return "redirect:/course/manage";
        }
        course.setTeaId(teacherId);

        logger.info("Attempting to add new course: {} by Teacher ID: {}", course.getCouName(), teacherId);
        try {
            boolean success = courseService.addCourse(course, couPicFile); // 使用 couPicFile
            if (success) {
                redirectAttributes.addFlashAttribute("successMessage", "课程添加成功！");
                logger.info("Course '{}' added successfully by Teacher ID: {}", course.getCouName(), teacherId);
            } else {
                redirectAttributes.addFlashAttribute("errorMessage", "课程添加失败，请检查输入并重试。");
                logger.warn("Failed to add course '{}' by Teacher ID: {}. Service returned false.", course.getCouName(), teacherId);
            }
        } catch (Exception e) {
            logger.error("Error adding course '{}' by Teacher ID {}: {}", course.getCouName(), teacherId, e.getMessage(), e);
            redirectAttributes.addFlashAttribute("errorMessage", "课程添加失败：系统错误，" + e.getMessage());
        }
        return "redirect:/course/manage";
    }

    /**
     * Display the course edit form.
     * @param id Course ID
     * @param model Model to pass data to the view
     * @param session HttpSession to get logged-in user info
     * @return The course edit page view
     */
    @GetMapping("/edit/{id}")
    public String editCourseForm(@PathVariable("id") Long id, Model model, HttpSession session, RedirectAttributes redirectAttributes) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null) {
            return "redirect:/login";
        }

        Long teacherId = teacherService.getTeacherIdByUserId(loggedInUser.getId());
        if (teacherId == null) {
            redirectAttributes.addFlashAttribute("errorMessage", "您无权编辑课程，因为您不是注册教师。");
            logger.warn("User ID {} is not a recognized teacher. Access denied to edit course form.", loggedInUser.getId());
            return "redirect:/course/manage";
        }

        Course course = courseService.getCourseById(id);
        if (course == null) {
            redirectAttributes.addFlashAttribute("errorMessage", "课程未找到。");
            logger.warn("Attempted to edit non-existent course ID: {} by user ID: {}", id, loggedInUser.getId());
            return "redirect:/course/manage";
        }

        if (!Objects.equals(course.getTeaId(), teacherId)) {
            redirectAttributes.addFlashAttribute("errorMessage", "您无权编辑此课程。");
            logger.warn("Unauthorized attempt to edit course ID {} by user ID: {} (Teacher ID: {}). Course owned by Teacher ID: {}.",
                    id, loggedInUser.getId(), teacherId, course.getTeaId());
            return "redirect:/course/manage";
        }
        model.addAttribute("course", course);
        model.addAttribute("loggedInUser", loggedInUser);
        logger.info("Teacher ID {} is accessing edit form for course ID: {}", teacherId, id);
        return "course-edit";
    }

    /**
     * Handle course edit form submission.
     * @param id Path variable for Course ID
     * @param course Course object from the form
     * @param couPicFile New MultipartFile for course cover image (optional)
     * @param session HttpSession to get logged-in user info
     * @param redirectAttributes RedirectAttributes for flash messages
     * @return Redirect to course management page or back to form
     */
    @PostMapping("/edit/{id}")
    public String updateCourse(@PathVariable("id") Long id,
                               @ModelAttribute("course") Course course,
                               @RequestParam(value = "couPicFile", required = false) MultipartFile couPicFile,
                               HttpSession session,
                               RedirectAttributes redirectAttributes) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null) {
            return "redirect:/login";
        }

        Long teacherId = teacherService.getTeacherIdByUserId(loggedInUser.getId());
        if (teacherId == null) {
            redirectAttributes.addFlashAttribute("errorMessage", "您无权更新课程，因为您不是注册教师。");
            logger.warn("User ID {} is not a recognized teacher. Failed to update course.", loggedInUser.getId());
            return "redirect:/course/manage";
        }

        Course existingCourse = courseService.getCourseById(id);
        if (existingCourse == null) {
            redirectAttributes.addFlashAttribute("errorMessage", "课程未找到。");
            logger.warn("Attempted to update non-existent course ID: {} by user ID: {}", id, loggedInUser.getId());
            return "redirect:/course/manage";
        }

        if (!Objects.equals(existingCourse.getTeaId(), teacherId)) {
            redirectAttributes.addFlashAttribute("errorMessage", "您无权更新此课程。");
            logger.warn("Unauthorized attempt to update course ID {} by user ID: {} (Teacher ID: {}). Course owned by Teacher ID: {}.",
                    id, loggedInUser.getId(), teacherId, existingCourse.getTeaId());
            return "redirect:/course/manage";
        }

        course.setId(id);
        course.setTeaId(existingCourse.getTeaId()); // Preserve original teacher ID

        logger.info("Attempting to update course ID: {} (Name: {}) by Teacher ID: {}", id, course.getCouName(), teacherId);
        try {
            boolean success = courseService.updateCourse(course, couPicFile); // 使用 couPicFile
            if (success) {
                redirectAttributes.addFlashAttribute("successMessage", "课程更新成功！");
                logger.info("Course ID {} updated successfully by Teacher ID: {}", id, teacherId);
            } else {
                redirectAttributes.addFlashAttribute("errorMessage", "课程更新失败，请检查输入并重试。");
                logger.warn("Failed to update course ID {} by Teacher ID: {}. Service returned false.", id, teacherId);
            }
        } catch (Exception e) {
            logger.error("Error updating course ID {} by Teacher ID {}: {}", id, teacherId, e.getMessage(), e);
            redirectAttributes.addFlashAttribute("errorMessage", "课程更新失败：系统错误，" + e.getMessage());
        }
        return "redirect:/course/manage";
    }

    /**
     * Display course details for students.
     * @param id Course ID
     * @param model Model to pass data to the view
     * @param session HttpSession to get logged-in user info
     * @param redirectAttributes RedirectAttributes for flash messages
     * @return The course detail view
     */
    @GetMapping("/detail/{id}")
    public String courseDetail(@PathVariable("id") Long id, Model model, HttpSession session, RedirectAttributes redirectAttributes) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null) {
            return "redirect:/login";
        }

        Course course = courseService.getCourseById(id);
        if (course == null) {
            redirectAttributes.addFlashAttribute("errorMessage", "课程未找到。");
            logger.warn("Course not found with ID: {} when accessed by user ID: {}", id, loggedInUser.getId());
            return "redirect:/course/browse"; // Redirect to a general browse page
        }

        // ****** 4. 新增的核心逻辑 ******
        // 获取与该课程相关的、正在进行的线下实践活动
        List<OfflinePractice> relatedPractices = practiceService.getPracticesByCourseId(id);
        model.addAttribute("relatedPractices", relatedPractices);
        // ****** 新增逻辑结束 ******

        List<Chapter> chapters = chapterService.getChaptersByCourseId(id);
        List<CommentDisplayDto> comments = commentService.getCommentsByCourseId(id);

        model.addAttribute("course", course);
        model.addAttribute("chapters", chapters);
        model.addAttribute("comments", comments);
        model.addAttribute("loggedInUser", loggedInUser);
        model.addAttribute("isStudent", "STUDENT".equals(loggedInUser.getRole()));
        model.addAttribute("isTeacher", "TEACHER".equals(loggedInUser.getRole()));
        model.addAttribute("newComment", new Comment()); // For the comment form

        boolean hasPurchased = false;
        boolean isLiked = false;
        boolean isCollected = false;

        if ("STUDENT".equals(loggedInUser.getRole())) {
            Student student = studentService.getStudentByUserId(loggedInUser.getId());
            if (student != null) {
                hasPurchased = studentService.hasStudentPurchasedCourse(student.getId(), id);
                isLiked = courseService.hasStudentLikedCourse(student.getId(), id);
                isCollected = courseService.hasStudentCollectedCourse(student.getId(), id);
            }
        }
        model.addAttribute("hasPurchased", hasPurchased);
        model.addAttribute("isLiked", isLiked);
        model.addAttribute("isCollected", isCollected);


        logger.info("User ID {} accessed course detail for course ID: {}", loggedInUser.getId(), id);
        return "course-detail";
    }

    /**
     * Handle the submission of a new comment on a course.
     * @param courseId The ID of the course being commented on.
     * @param comment The Comment object bound from the form (contains content and rating).
     * @param session HttpSession to get logged-in user info.
     * @param redirectAttributes RedirectAttributes for flash messages.
     * @return Redirect to the course detail page.
     */
    @PostMapping("/detail/{courseId}/addComment")
    public String addCourseComment(@PathVariable("courseId") Long courseId,
                                   @ModelAttribute("newComment") Comment comment,
                                   HttpSession session,
                                   RedirectAttributes redirectAttributes) {

        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null) {
            redirectAttributes.addFlashAttribute("errorMessage", "请先登录后再发表评论。");
            return "redirect:/login"; // Or redirect to course detail if login is modal
        }

        // 确保只有学生可以评论 (如果业务逻辑如此要求)
        if (!"STUDENT".equals(loggedInUser.getRole())) {
            redirectAttributes.addFlashAttribute("errorMessage", "只有学生用户才能发表评论。");
            logger.warn("Non-student user (ID: {}, Role: {}) attempted to add comment to course ID: {}",
                    loggedInUser.getId(), loggedInUser.getRole(), courseId);
            return "redirect:/course/detail/" + courseId;
        }

        // 获取登录用户对应的学生ID（student表的主键ID）
        Student student = studentService.getStudentByUserId(loggedInUser.getId());
        if (student == null) {
            redirectAttributes.addFlashAttribute("errorMessage", "未找到您的学生信息，无法发表评论。");
            logger.error("No student record found for logged in user ID: {}", loggedInUser.getId());
            return "redirect:/course/detail/" + courseId;
        }

        comment.setCourseId(courseId);
        // 关键修改：将 student.id 赋值给 Comment 对象的 userId 属性
        comment.setUserId(student.getId());

        try {
            boolean success = commentService.addComment(comment);
            if (success) {
                redirectAttributes.addFlashAttribute("successMessage", "评论发表成功！");
                logger.info("User ID {} (Student ID {}) successfully added comment to course ID: {}", loggedInUser.getId(), student.getId(), courseId);
            } else {
                redirectAttributes.addFlashAttribute("errorMessage", "评论发表失败，请稍后重试。");
                logger.warn("CommentService.addComment returned false for user ID {} (Student ID {}) and course ID: {}", loggedInUser.getId(), student.getId(), courseId);
            }
        } catch (IllegalArgumentException e) {
            logger.warn("Validation error when user ID {} (Student ID {}) adding comment to course ID {}: {}", loggedInUser.getId(), student.getId(), courseId, e.getMessage());
            redirectAttributes.addFlashAttribute("errorMessage", "评论发表失败：" + e.getMessage());
        } catch (Exception e) {
            logger.error("Error adding comment for course ID {} by user ID {} (Student ID {}): {}", courseId, loggedInUser.getId(), student.getId(), e.getMessage(), e);
            redirectAttributes.addFlashAttribute("errorMessage", "评论发表失败：发生系统错误。");
        }

        return "redirect:/course/detail/" + courseId;
    }


    /**
     * Handle course deletion.
     * @param id Course ID to delete
     * @param session HttpSession to get logged-in user info
     * @param redirectAttributes RedirectAttributes for flash messages
     * @return Redirect to course management page
     */
    @PostMapping("/delete/{id}")
    public String deleteCourse(@PathVariable("id") Long id, HttpSession session, RedirectAttributes redirectAttributes) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null) {
            return "redirect:/login";
        }

        Long teacherId = teacherService.getTeacherIdByUserId(loggedInUser.getId());

        // 权限检查：必须是教师，且是课程所有者
        if (!"TEACHER".equals(loggedInUser.getRole()) || teacherId == null) {
            redirectAttributes.addFlashAttribute("errorMessage", "您无权删除课程，因为您不是该课程的教师。");
            logger.warn("Unauthorized delete attempt: User ID {} (Role: {}) is not a recognized teacher or not teacher for course ID {}.",
                    loggedInUser.getId(), loggedInUser.getRole(), id);
            return "redirect:/course/manage";
        }

        Course existingCourse = courseService.getCourseById(id);
        if (existingCourse == null) {
            redirectAttributes.addFlashAttribute("errorMessage", "课程未找到或已删除。");
            logger.warn("Attempted to delete non-existent course ID: {} by user ID: {}", id, loggedInUser.getId());
            return "redirect:/course/manage";
        }

        if (!Objects.equals(existingCourse.getTeaId(), teacherId)) {
            redirectAttributes.addFlashAttribute("errorMessage", "您只能删除您自己的课程。");
            logger.warn("Unauthorized delete attempt: User ID {} (Teacher ID: {}) attempted to delete course ID {} owned by Teacher ID: {}.",
                    loggedInUser.getId(), teacherId, id, existingCourse.getTeaId());
            return "redirect:/course/manage";
        }

        try {
            boolean success = courseService.deleteCourse(id, teacherId); // 修正：调用带有 teacherId 参数的 deleteCourse
            if (success) {
                redirectAttributes.addFlashAttribute("successMessage", "课程删除成功！");
                logger.info("Course ID {} deleted successfully by Teacher ID: {}", id, teacherId);
            } else {
                redirectAttributes.addFlashAttribute("errorMessage", "课程删除失败，请稍后再试。");
                logger.warn("Failed to delete course ID {} by Teacher ID: {}. Service returned false.", id, teacherId);
            }
        } catch (RuntimeException e) {
            logger.error("Runtime error while deleting course ID {} by Teacher ID: {}. Error: {}", id, teacherId, e.getMessage(), e);
            redirectAttributes.addFlashAttribute("errorMessage", "课程删除失败：" + e.getMessage());
        } catch (Exception e) {
            logger.error("An unexpected error occurred while deleting course ID {} by Teacher ID: {}: {}", id, teacherId, e.getMessage(), e);
            redirectAttributes.addFlashAttribute("errorMessage", "课程删除失败：系统错误，请稍后再试。");
        }
        return "redirect:/course/manage";
    }


    /**
     * Display a list of all available non-deleted courses for students to browse.
     * @param model Model to pass data to the view
     * @param session HttpSession to get logged-in user info
     * @return The browse courses page view
     */
    @GetMapping("/browse")
    public String browseCourses(Model model, HttpSession session) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null) {
            return "redirect:/login";
        }

        List<Course> courses = courseService.getAllCourses();
        model.addAttribute("courses", courses);
        model.addAttribute("loggedInUser", loggedInUser);
        logger.info("User ID {} accessed browse courses page. Found {} courses.", loggedInUser.getId(), courses.size());
        return "browse-courses";
    }

    /**
     * API endpoint to toggle (add/remove) a course like.
     * @param courseId The ID of the course to like/unlike.
     * @param session HttpSession to get logged-in user info.
     * @return A JSON response indicating success/failure and the new like status.
     */
    @PostMapping("/api/like/{courseId}")
    @ResponseBody
    public Map<String, Object> toggleLikeCourse(@PathVariable("courseId") Long courseId, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        User loggedInUser = (User) session.getAttribute("loggedInUser");

        if (loggedInUser == null || !"STUDENT".equals(loggedInUser.getRole())) {
            response.put("success", false);
            response.put("message", "请先以学生身份登录。");
            return response;
        }

        Student student = studentService.getStudentByUserId(loggedInUser.getId());
        if (student == null) {
            response.put("success", false);
            response.put("message", "未找到您的学生信息。");
            return response;
        }

        try {
            boolean isLiked = courseService.toggleCourseLike(student.getId(), courseId);
            response.put("success", true);
            response.put("isLiked", isLiked);
            response.put("message", isLiked ? "点赞成功！" : "取消点赞成功！");
            logger.info("Student ID {} toggled like for course ID {}. New status: {}", student.getId(), courseId, isLiked);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "操作失败：" + e.getMessage());
            logger.error("Error toggling like for course ID {} by student ID {}: {}", courseId, student.getId(), e.getMessage(), e);
        }
        return response;
    }

    /**
     * API endpoint to toggle (add/remove) a course collection.
     * @param courseId The ID of the course to collect/uncollect.
     * @param session HttpSession to get logged-in user info.
     * @return A JSON response indicating success/failure and the new collection status.
     */
    @PostMapping("/api/collect/{courseId}")
    @ResponseBody
    public Map<String, Object> toggleCollectCourse(@PathVariable("courseId") Long courseId, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        User loggedInUser = (User) session.getAttribute("loggedInUser");

        if (loggedInUser == null || !"STUDENT".equals(loggedInUser.getRole())) {
            response.put("success", false);
            response.put("message", "请先以学生身份登录。");
            return response;
        }

        Student student = studentService.getStudentByUserId(loggedInUser.getId());
        if (student == null) {
            response.put("success", false);
            response.put("message", "未找到您的学生信息。");
            return response;
        }

        try {
            boolean isCollected = courseService.toggleCourseCollect(student.getId(), courseId);
            response.put("success", true);
            response.put("isCollected", isCollected);
            response.put("message", isCollected ? "收藏成功！" : "取消收藏成功！");
            // CORRECTED LINE: Removed the backslash before the closing double quote
            logger.info("Student ID {} toggled collection for course ID {}. New status: {}", student.getId(), courseId, isCollected);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "操作失败：" + e.getMessage());
            logger.error("Error toggling collection for course ID {} by student ID {}: {}", courseId, student.getId(), e.getMessage(), e);
        }
        return response;
    }

    /**
     * Display a list of courses collected by the logged-in student.
     * @param model Model to pass data to the view
     * @param session HttpSession to get logged-in user info
     * @param redirectAttributes RedirectAttributes for flash messages
     * @return The collected courses page view
     */
    @GetMapping("/collected-courses") // Changed this annotation to match the URL from the 404 error
    public String viewCollectedCourses(Model model, HttpSession session, RedirectAttributes redirectAttributes) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null) {
            return "redirect:/login";
        }

        // 确保只有学生可以访问收藏列表
        if (!"STUDENT".equals(loggedInUser.getRole())) {
            redirectAttributes.addFlashAttribute("errorMessage", "只有学生用户才能查看收藏课程。");
            logger.warn("Non-student user (ID: {}, Role: {}) attempted to access collected courses.",
                    loggedInUser.getId(), loggedInUser.getRole());
            return "redirect:/"; // 或者重定向到其他合适的页面
        }

        Student student = studentService.getStudentByUserId(loggedInUser.getId());
        if (student == null) {
            redirectAttributes.addFlashAttribute("errorMessage", "未找到您的学生信息，无法查看收藏课程。");
            logger.error("No student record found for logged in user ID: {} when accessing collected courses.", loggedInUser.getId());
            return "redirect:/";
        }

        List<Course> collectedCourses = courseService.getCollectedCoursesByStudentId(student.getId());
        model.addAttribute("courses", collectedCourses);
        model.addAttribute("loggedInUser", loggedInUser);
        logger.info("Student ID {} accessed collected courses page. Found {} collected courses.", student.getId(), collectedCourses.size());
        return "collected-courses"; // You'll need to create a Thymeleaf template named collected-courses.html
    }
}